import { defineConfig, loadEnv, type ServerOptions } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'url'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd())
  
  const config: any = {
    plugins: [vue()],
    css: {
      // CSS 预处理器
      preprocessorOptions: {
          // 定义全局 SCSS 变量
          scss: {
              javascriptEnabled: true,
              additionalData: "@use '/src/styles/variables.scss' as *;",
          },
      },
    },
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
        }
    },
    base: '/',
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      rollupOptions: {
        output: {
          assetFileNames: 'assets/[name].[hash][extname]'
        }
      },
      // 生产环境移除 console
      minify: 'terser',
      terserOptions: {
        compress: {
          // drop_console: true,
          drop_debugger: true
        }
      }
    }
  }

  // 根据环境配置不同的服务器设置
  if (mode === 'development') {
    // 开发环境：使用代理
    config.server = {
      host: '0.0.0.0',
      port: 3000,
      proxy: {
        /*  '/api/document/parse_bid_file': {
          target: env.VITE_APP_DOCUMENT_URL,
          changeOrigin: true,
          rewrite: (path: string) => path.replace(/^\/api/, '')
        }, */
        '/api': {
          target: env.VITE_APP_PROXY_TARGET,
          changeOrigin: true,
          rewrite: (path: string) => path.replace(/^\/api/, '')
        },
        
      }
    } as ServerOptions
  }
   // 预览环境配置
   else if (mode === 'production') {
    config.preview = {
      host: '0.0.0.0',
      port: 4173,
      strictPort: true,
      proxy: {
        [env.VITE_APP_BASE_API]: {
          target: env.VITE_APP_API_URL,
          changeOrigin: true,
          rewrite: (path: string) => path.replace(new RegExp('^' + env.VITE_APP_BASE_API), '')
        }
      }
    }
  }
   else {
    // 测试环境：直接访问测试服务器
    config.server = {
      host: 'localhost',
      port: 3000
    } as ServerOptions
  }

  return config
})
